<template>
  <div class="shell">
    <!-- <h1>产品集市</h1> -->
    <div class="action-bar">
      <div class="tab-group">
        <button class="tab-btn" :class="{ active: activeTab === 'sell' }" @click="handleTabChange('sell')">
          出售
        </button>
        <button class="tab-btn" :class="{ active: activeTab === 'buy' }" @click="handleTabChange('buy')">
          收购
        </button>
      </div>

      <div class="search-group">


        <PublishButton v-if="activeTab === 'buy' && store.userdata.role_name === 'dealer'" :type="activeTab"
          @publish="handleRefresh" />

        <PublishGoodsButton v-if="activeTab === 'sell' && store.userdata.role_name === 'farmer'" :type="activeTab"
          @fresh="handleRefresh" />
        <el-button type="primary" :icon="Refresh" @click="handleRefresh" :loading="loading">
          刷新
        </el-button>
        <div class="search-box">
          <el-input v-model="searchText" :placeholder="activeTab === 'buy' ? '搜索公告标题' : '搜索农产品'" class="search-input"
            clearable @clear="resetSearch" @keyup.enter="handleSearch">
            <template #prefix>
              <el-icon>
                <Search />
              </el-icon>
            </template>
          </el-input>
          <el-button type="success" @click="handleSearch" :loading="searching">搜索</el-button>
        </div>
      </div>
    </div>

    <div class="content-grid" v-loading="loading" element-loading-text="加载中...">
      <!-- 收购列表 -->
      <template v-if="activeTab === 'buy'">
        <buyGoods v-for="(goods) in paginatedGoods" :key="goods.article_id" :data="goods"
          @view-detail="handleViewDetail" />
      </template>

      <!-- 出售列表 -->
      <template v-else>
        <sellGoods v-for="(goods) in paginatedGoods" :key="goods.product_id" :goods="goods" :showDetail="true"
          :showOffShelf="false" :showStatus="false" />
      </template>
    </div>

    <!-- 出售 -->
    <!-- <section v-if="activeTab === 'sell'" v-loading="loading" element-loading-text="加载中...">
      <sellGoods v-for="(goods) in paginatedGoods" :key="goods.product_id" :goods="goods" :showDetail="true"
        :showOffShelf="false" :showStatus="false" />
    </section> -->

    <!-- 收购 -->
    <!-- <section v-else-if="activeTab === 'buy'" v-loading="loading" element-loading-text="加载中...">
      <buyGoods class="buygoods" v-for="(goods) in paginatedGoods" :key="goods.article_id" :data="goods"
        @view-detail="handleViewDetail" />
    </section> -->

    <el-empty v-if="!loading && paginatedGoods.length === 0" description="暂无数据" />

    <!-- 分页 -->
    <!-- <footer v-if="paginatedGoods.length !== 0"> -->
    <!-- 语法上的差异，具名 v-model 语法可能会在IDE里报错，但是这个语法是没问题的 -->
    <!-- <el-pagination background large layout="prev, pager, next" :page-size="8" :current-page="currentPage"
        :total="activeTab === 'sell' ? totalCount : buyTotalCount"  @current-change="handlePageChange"/>
    </footer> -->

    <div class="pagination" v-show="paginatedGoods.length > 0">
      <el-pagination background large layout="prev, pager, next" :page-size="8" :current-page="currentPage"
        :total="activeTab === 'sell' ? totalCount : buyTotalCount" @current-change="handlePageChange" />
    </div>

  </div>
</template>

<script setup>
// 商店页面组件
import { ref, onMounted, inject, computed } from 'vue';
import sellGoods from '../components/SellGoodsItem.vue'
import PublishButton from '../components/PublishButton.vue';
import buyGoods from '../components/PurchaseItem.vue';
import { ElMessage } from 'element-plus';
import PublishGoodsButton from '../components/PublishGoodsButton.vue';
import { useMainStore } from '@/stores';
import { useRouter } from 'vue-router'
import { Search, RefreshRight } from '@element-plus/icons-vue';

const Refresh = RefreshRight;
const store = useMainStore();
const router = useRouter()
// 使用 inject 获取全局提供的 axios 实例
const $axios = inject('$axios')
const $tools = inject('$tools')

const sellGoodsList = ref([]);
const buyGoodsList = ref([]);
const loading = ref(false)
// 分页
const currentPage = ref(1);
const totalCount = ref(0);
const buyTotalCount = ref(0);

// 分页后的商品列表
const paginatedGoods = computed(() => {
  const start = (currentPage.value - 1) * 8;
  const end = start + 8;
  if (activeTab.value === 'sell') {
    return sellGoodsList.value.slice(start, end);
  }
  else if (activeTab.value === 'buy') {
    return buyGoodsList.value.slice(start, end);
  }
  return [];
});

// 收购和出售切换
const activeTab = ref('sell');
const handleTabChange = (tab) => {
  if(tab == activeTab.value) return;
  activeTab.value = tab;
  currentPage.value = 1;
  store. setCurrentPage(1);
  searchText.value = ''

  store.setActiveTap(tab);
  if (searchText.value) {
    resetSearch()
  } else if (tab === 'sell') {
    loading.value = true;

    fetchSellGoods();
  } else if (tab === 'buy') {
    loading.value = true
    fetchBuyGoods();
  }
};

onMounted(async () => {
  currentPage.value = store.currentPage;
  activeTab.value = store.activeTap;
  if (activeTab.value === 'sell')
    fetchSellGoods();
  else if (activeTab.value === 'buy') {
    fetchBuyGoods()
  }
});

async function fetchSellGoods() {
  try {
    const sellResponse = await $axios.get('/agri_products/farmer');
    const data = sellResponse.data.data;
    // console.log(data)
    // 使用 toLocaleString 转换 created_at 字段
    const processedData = data.map(item => {
      const date = new Date(item.created_at);
      const localDateString = date.toLocaleString();
      return {
        ...item,
        created_at: localDateString
      };
    });

    sellGoodsList.value = processedData;
    totalCount.value = sellGoodsList.value.length;
  } catch (error) {
    console.error("Failed to fetch sell goods:", error);
  } finally {
    loading.value = false
  }
}

async function fetchBuyGoods() {
  try {
    // 获取收购列表
    const buyResponse = await $axios.get('/article/dealer');
    // console.log(buyResponse.data.data)
    if (buyResponse.data.code === 200) {
      const data = buyResponse.data.data
      buyGoodsList.value = data.filter(item => item.title.includes('收购'))
      buyTotalCount.value = buyGoodsList.value.length
      // console.log(buyResponse.data.data)
      store.setBuyList(buyGoodsList.value)
    } else {
      ElMessage.error(buyResponse.data.msg || '获取数据失败')
    }
    // const data = buyResponse.data.data;

    // const formattedData = data.map(item => {
    //   const newItem = { ...item };
    //   newItem.deadline = new Date(item.deadline).toLocaleString();
    //   newItem.published_at = new Date(item.published_at).toLocaleString();
    //   return newItem;
    // });

    // buyGoodsList.value = formattedData;
    // buyGoodsList.value = buyResponse.data.data;
    // buyTotalCount.value = buyGoodsList.value.length;
  } catch (error) {
    console.error("Failed to fetch sell goods:", error);
  } finally {
    loading.value = false
  }
}

// 处理查看详情
const handleViewDetail = (articleId) => {
  const list = buyGoodsList.value;
  const currentArticle = list.find(item => item.article_id === articleId)
  store.setCurrentArticle(currentArticle)
  router.push(`/home/artiDetail/${articleId}`)
}

// 处理刷新
const handleRefresh = () => {
  searchText.value = ''
  currentPage.value = 1;
  store.setCurrentPage(1)
  searchText.value = ''
  loading.value = true
  if (searchText.value) {
    resetSearch()
  } else if (activeTab.value === 'sell') {
    fetchSellGoods();
  } else if (activeTab.value === 'buy') {
    fetchBuyGoods();
  }
}
// 处理页面切换
const handlePageChange = (page) => {
  currentPage.value = page
  store.setCurrentPage(page)
  // window.scrollTo({
  //   top: 0,
  //   behavior: 'smooth'
  // })
}


// 搜索处理
const searchText = ref('')
const searching = ref(false)
const handleSearch = async () => {
  if (!searchText.value.trim()) {
    $tools.alertMsg('请输入搜索关键词', 'error')
    return
  }

  searching.value = true
  currentPage.value = 1
  store.setCurrentPage(1)

  try {
    if (activeTab.value === 'sell') {
      const response = await $axios.get('/agri_products/search', {
        params: {
          title: searchText.value.trim(),
          role: 'farmer'
        }
      })

      if (response.data.code === 200) {
        const searchResults = response.data.data
        sellGoodsList.value = searchResults.map(item => ({
          ...item,
          created_at: new Date(item.created_at).toLocaleString()
        }))
        totalCount.value = sellGoodsList.value.length
      } else {
        ElMessage.error()
        $tools.alertMsg(response.data.msg || '搜索失败', 'error')
      }
    }
    else if (activeTab.value === 'buy') {
      const response = await $axios.get('/article/search', {
        params: {
          title: searchText.value.trim(),
          role: 'dealer'
        }
      })

      if (response.data.code === 200) {
        const searchResults = response.data.data
        buyGoodsList.value = searchResults.map(item => ({
          ...item,
          created_at: new Date(item.created_at).toLocaleString()
        }))
        
        buyTotalCount.value = buyGoodsList.value.length
      }
    }
  } catch (error) {
    console.error('搜索失败:', error)
    $tools.alertMsg('搜索失败，请稍后重试', 'error')
  } finally {
    searching.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  searchText.value = ''
  currentPage.value = 1
  store.setCurrentPage(1)
  if (activeTab.value === 'sell')
    fetchSellGoods();
  else if (activeTab.value == 'buy ') fetchBuyGoods();
}

// 处理发布成功
// const handlePublishSuccess = (postData) => {
//   if (!postData) return;

//   if (activeTab.value === 'buy') {
//     // 确保数据格式正确
//     const newArticle = {
//       ...postData,
//       article_id: postData.id || postData.article_id, // 兼容两种 id 字段名
//       title: postData.title || `${postData.product_name}收购公告`,
//       created_at: postData.created_at || new Date().toLocaleString()
//     };
//     buyList.value.unshift(newArticle);
//     store.addArticle(newArticle, 'buy');
//   }
//   currentPage.value = 1;
//   store.setCurrentPage(1)
// }
</script>

<style lang="less" scoped>
.shell {
  padding: 20px;

  h1 {
    font-size: 24px;
    margin-bottom: 20px;
    color: #319A19;
  }


  .action-bar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

    .tab-group {
      display: flex;
      gap: 10px;

      .tab-btn {
        min-width: 80px;
        height: 32px;
        line-height: 30px;
        padding: 0 15px;
        border: 1px solid #dcdfe6;
        background: #fff;
        color: #606266;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          border-color: #319A19;
          color: #319A19;
        }

        &.active {
          background: #319A19;
          border-color: #319A19;
          color: #fff;
        }
      }
    }

    .search-group {
      display: flex;
      align-items: center;
      gap: 16px;

      .search-box {
        display: flex;
        gap: 8px;

        .search-input {
          width: 300px;

          :deep(.el-input__wrapper) {
            box-shadow: 0 0 0 1px #319A19 inset;

            &.is-focus {
              box-shadow: 0 0 0 1px #319A19 inset;
            }
          }
        }
      }
    }
  }
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
  min-height: 200px;
}

// section {
//   display: flex;
//   justify-content: space-between;
//   flex-wrap: wrap;
//   width: 1160px;
//   padding: 0px;
//   margin: 0px;
//   .buygoods {
//     width:570px;
//   }
// }

// footer {
//   width: 1200px;
//   height: 72px;
//   display: flex;
//   justify-content: center;
//   background: #fff;
//   border-radius: 4px;
//   box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

//   back {
//     width: 30px;
//     border: 1px solid #319A19;
//   }

//   right {
//     width: 30px;
//     border: 1px solid #319A19;
//   }

//   span {
//     width: 30px;
//     height: 30px;
//     line-height: 30px;
//     text-align: center;
//     margin-left: 5px;
//     margin-right: 5px;
//     border: 1px solid #319A19;
//     color: #000;
//     background-color: white;

//     &.active {
//       background-color: #319A19;
//       color: white;
//     }

//     &.disabled {
//       background-color: #ddd;
//       color: #666;
//       pointer-events: none;
//     }
//   }
// }

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

@media screen and (max-width: 1200px) {
  .shell {
    .content-grid {
      grid-template-columns: 1fr;
    }
  }
}

@media screen and (max-width: 768px) {
  .shell {
    padding: 12px;

    .action-bar {
      flex-direction: column;
      gap: 16px;

      .search-group {
        width: 100%;
        flex-direction: column;

        .search-box {
          width: 100%;

          .search-input {
            width: 100%;
          }
        }
      }
    }
  }
}
</style>